﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using ARchGL.Declaration.Platform.Service;
using ARchGL.Declaration.Platform.Service.Dtos;
using TDF.Core.Exceptions;
using TDF.Core.Models;

namespace ARchGL.Declaration.Platform.Web.Controllers.Apis
{
    /// <summary>
    /// 系统相关接口
    /// </summary>
    public class SystemController : ApiControllerBase
    {
        #region 注入服务

        /// <summary>
        /// 管理员接口
        /// </summary>
        public readonly IAdminService AdminService;
        /// <summary>
        /// 系统服务
        /// </summary>
        private readonly ISystemService SystemService;

        /// <summary>
        /// 项目服务
        /// </summary>
        private readonly IProjectService ProjectService;

        /// <summary>
        /// 初始化服务
        /// </summary>
        public SystemController(IAdminService adminService, ISystemService systemService, IProjectService projectService)
        {
            AdminService = adminService;
            SystemService = systemService;
            ProjectService = projectService;
        }

        #endregion

        #region 账户相关

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="from">登录信息</param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult Login([FromBody]LoginFrom from)
        {
            var model = SystemService.Login(from.Name, from.Password);
            if (model.Type == Domain.Entities.AccountType.项目帐号)
            {
                //项目帐号登录时赋值 ProjectId
                var project = ProjectService.GetProjectByCode(model.Number);
                if (project != null) model.ProjectId = project.Id;

                //工程数量，用于判断是否跳转至工程详细页面
                model.ProjectChildCount = ProjectService.GetProjectChildCountId(project.Id);
            }
            else if (model.Type == Domain.Entities.AccountType.企业帐号)
            {
                //var project = ProjectService.GetProjectByCode(model.Number);
                //if (project != null) model.ProjectId = project.Id;
            }
            return Success(model);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult Logout([FromBody]LogoutFrom from)
        {
            SystemService.Logout(from.LoginToken);
            return Success();
        }

        /// <summary>
        /// 创建账号（审核、企业、项目）
        /// </summary>
        /// <param name="from">账号信息</param>
        /// <returns></returns>
        public ApiResult CreateAccount([FromBody]AccountFrom from)
        {
            var dto = from.Merge<AccountFrom, AccountDto>();
            SystemService.InitLoginToken(from.LoginToken);
            var model = SystemService.CreateAccount(dto, from.AreaId);
            return Success(model);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="from">密码信息</param>
        /// <returns></returns>
        public ApiResult ChangePassword([FromBody]ChangePasswordFrom from)
        {
            SystemService.InitLoginToken(from.LoginToken);
            SystemService.ChangePassword(from.AccountId, from.Password);
            return Success(true);
        }

        /// <summary>
        /// 修改帐号名称
        /// </summary>
        /// <param name="from">帐号信息</param>
        /// <returns></returns>
        public ApiResult ChangeAccountName([FromBody]ChangeAccountNameFrom from)
        {
            SystemService.InitLoginToken(from.LoginToken);
            SystemService.ChangeAccountName(from.AccountId, from.Name);
            return Success(true);
        }

        /// <summary>
        /// 修改帐号状态
        /// </summary>
        /// <param name="from">帐号信息</param>
        /// <returns></returns>
        public ApiResult ChangeAccountStatus([FromBody]ChangeAccountStatusFrom from)
        {
            SystemService.InitLoginToken(from.LoginToken);
            SystemService.ChangeAccountStatus(from.AccountId, from.Remark);
            return Success(true);
        }

        /// <summary>
        /// 重置密码为帐号（通过AccountId）
        /// </summary>
        /// <param name="from">帐号信息</param>
        /// <returns></returns>
        public ApiResult ResetPasswordById([FromBody]ResetPasswordFrom from)
        {
            SystemService.InitLoginToken(from.LoginToken);
            SystemService.ResetPasswordById(from.AccountId);
            return Success(true);
        }

        /// <summary>
        /// 重置密码为帐号（通过Number）
        /// </summary>
        /// <param name="from">帐号信息</param>
        /// <returns></returns>
        public ApiResult ResetPasswordByNumber([FromBody]ResetPasswordFrom from)
        {
            SystemService.InitLoginToken(from.LoginToken);
            SystemService.ResetPasswordByNumber(from.Number);
            return Success(true);
        }

        /// <summary>
        /// 获取帐号信息
        /// </summary>
        /// <param name="from">帐号Id</param>
        /// <returns></returns>
        public ApiResult QueryAccountById([FromBody]AccountIdFrom from)
        {
            var entity = SystemService.GetAccountById(from.AccountId);
            return Success(entity);
        }

        /// <summary>
        /// 获取当前区县下最大质监员编号
        /// </summary>
        /// <param name="from">登录信息</param>
        /// <returns></returns>
        public ApiResult QueryAccountMaxNumber([FromBody]BaseFrom from)
        {
            SystemService.InitLoginToken(from.LoginToken);
            var number = SystemService.GetAccountMaxNumber();
            return Success(number.ToString());
        }

        /// <summary>
        /// 获取帐号数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult QueryAccountList([FromBody]AccountCriteria criteria)
        {
            var list = SystemService.GetAccountList(criteria);
            return Success(list);
        }

        /// <summary>
        /// 获取企业帐号缓存数据
        /// </summary>
        /// <returns></returns>
        public ApiResult QueryCompanyCacheAccountList()
        {
            var list = SystemService.GetCompanyCacheAccountList();
            return Success(list);
        }

        /// <summary>
        /// 获取企业帐号-分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult QueryCompanyAccountPagedList([FromBody]AccountCriteria criteria)
        {
            var result = SystemService.GetCompanyAccountPagedList(criteria);
            #region 赋值隶属关系

            var accountIdList = result.Item2.Rows.Select(x => x.AccountIds).ToList();
            var idList = new List<Guid>();
            foreach (var item in accountIdList.Where(x => !string.IsNullOrWhiteSpace(x)))
            {
                foreach (var asdf in item.Split(','))
                {
                    Guid.TryParse(asdf, out Guid id);
                    if (id != Guid.Empty) idList.Add(id);
                }
            }
            if (idList.Count > 0)
            {
                var parentAccountList = SystemService.GetAccountList(new AccountCriteria { IdList = idList });

                foreach (var item in result.Item2.Rows)
                {
                    if (string.IsNullOrWhiteSpace(item.AccountIds)) continue;
                    var ids = new List<Guid>();
                    foreach (var asdf in item.AccountIds.Split(','))
                    {
                        Guid.TryParse(asdf, out Guid id);
                        if (id != Guid.Empty) ids.Add(id);
                    }

                    if (ids.Count > 0)
                        item.ParentAccountName = string.Join(" | ", parentAccountList.OrderBy(x => x.Type).Where(x => ids.Contains(x.Id)).Select(x => x.Name).ToList());
                }
            }

            #endregion
            return Success(result.Item1, result.Item2);
        }

        /// <summary>
        /// 获取区县帐号-分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult QueryAreaAccountPagedList([FromBody]AccountCriteria criteria)
        {
            var result = SystemService.GetAreaAccountPagedList(criteria);
            return Success(result.Item1, result.Item2);
        }

        /// <summary>
        /// 获取账户分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult QueryAccountPagedList([FromBody]AccountCriteria criteria)
        {
            if (!string.IsNullOrWhiteSpace(criteria.AccountId))
            {
                Guid.TryParse(criteria.AccountId, out Guid accountId);
                var entity = SystemService.GetAccountById(accountId);
                if (entity == null || entity.Type == Domain.Entities.AccountType.管理员) criteria.AccountId = string.Empty;
            }

            //if (criteria.Type == Domain.Entities.AccountType.企业帐号)
            //    return Success(SystemService.GetCompanyCacheAccountList());

            var result = SystemService.GetAccountPagedList(criteria);

            #region 赋值隶属关系

            var accountIdList = result.Item2.Rows.Select(x => x.AccountIds).ToList();
            var idList = new List<Guid>();
            foreach (var item in accountIdList.Where(x => !string.IsNullOrWhiteSpace(x)))
            {
                foreach (var asdf in item.Split(','))
                {
                    Guid.TryParse(asdf, out Guid id);
                    if (id != Guid.Empty) idList.Add(id);
                }
            }
            if (idList.Count > 0)
            {
                var parentAccountList = SystemService.GetAccountList(new AccountCriteria { IdList = idList });

                foreach (var item in result.Item2.Rows)
                {
                    if (string.IsNullOrWhiteSpace(item.AccountIds)) continue;
                    var ids = new List<Guid>();
                    foreach (var asdf in item.AccountIds.Split(','))
                    {
                        Guid.TryParse(asdf, out Guid id);
                        if (id != Guid.Empty) ids.Add(id);
                    }

                    if (ids.Count > 0)
                        item.ParentAccountName = string.Join(" | ", parentAccountList.OrderBy(x => x.Type).Where(x => ids.Contains(x.Id)).Select(x => x.Name).ToList());
                }
            }

            #endregion

            return Success(result.Item1, result.Item2);
        }

        /// <summary>
        /// 获取帐号登录日志 分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult QuerytLoggingPagedList([FromBody]LoggingCriteria criteria)
        {
            var entity = SystemService.GetAccountById(criteria.AccountId);
            if (entity == null) throw new KnownException("账号不存在");

            var list = SystemService.GetLoggingPagedList(criteria);
            return Success(list);
        }

        #endregion

        #region 角色相关

        /// <summary>
        /// 获取模块（菜单）分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ApiResult QueryModulesPagedList([FromBody]ModulesCriteria criteria)
        {
            var list = SystemService.GetModulesPagedList(criteria);
            return Success(list);
        }

        #endregion

        /// <summary>
        /// 获取系统当前时间
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ApiResult GetTime()
        {
            return Success(string.Empty, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}